﻿using System;

namespace GestureMatching.DataStructure
{
    public class TimingQueue
    {
        private TimingNode headNode = null;
        private TimingNode tailNode = null;
        private int length = 0;

        public TimingQueue()
        {
            headNode = new TimingNode();
            tailNode = headNode;
        }

        public TimingNode Pop()
        {
            TimingNode outQueueNode = tailNode;

            tailNode = tailNode.previous;
            tailNode.next.previous = null;
            tailNode.next = null;

            length--;

            return outQueueNode;
        }

        public void Push(TimingNode node)
        {
            tailNode.next = node;
            node.previous = tailNode;
            tailNode = node;

            length++;

            DeleteOutdatedNode();
        }

        public bool IsEmpty()
        {
            if (tailNode == headNode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public int GetLength()
        {
            return length;
        }

        public TimingNode GetHeadNode()
        {
            return headNode;
        }

        public TimingNode GetTailNode()
        {
            return tailNode;
        }

        public void DeleteOutdatedNode()
        {
            if (IsEmpty())
            {
                return;
            }

            DateTime lastTime = tailNode.createTime;
            int timeThreshold = 120;

            while (lastTime.Subtract(headNode.next.createTime).Seconds > timeThreshold)
            {
                headNode.next = headNode.next.next;

                if (headNode.next != null)
                {
                    headNode.next.previous.next = null;
                    headNode.next.previous.previous = null;
                    headNode.next.previous = headNode;
                }
                else
                {
                    tailNode.previous = null;
                    tailNode = headNode;
                }
            }
        }

        public override string ToString()
        {
            String result = "";
            TimingNode tempNode = headNode;

            while ((tempNode = tempNode.next) != null)
            {
                result += tempNode.ToString() + ",";
            }

            if (result.Length > 2)
            {
                result = result.Substring(0, result.Length - 1);
                result = "[" + result + "]";
            }

            return result;
        }
    }
}